import React from 'react';
import { Form, Input, Button, Icon } from 'antd';
import { setValue } from 'shared/utils/localStorageApi.js';
import './index.less';

const FormItem = Form.Item;

export default class Login extends React.Component {

  state = {
    loading: false,
    errorMsg: ''
  }

  loginReq = (params) => {
    const { userLogin, system, updateLoginUserInfo, history } = this.props;
    this.setState({
      loading: true
    });
    userLogin(params).then(() => {
      const { loginStore } = this.props;
      const loginUser = loginStore.login.get('loginData');
      const loginMessage = loginStore.login.get('loginMessage');
      if (loginUser) {
        setValue('userInfo', loginUser.toJS());
        this.setState({
          loading: false
        });
        let pathname = sessionStorage.getItem('pathname');
        if (pathname) {
          history.push(pathname);
        } else{
          history.push('/');
        }
      } else {
        this.setState({
          errorMsg: loginMessage,
          loading: false
        });
      }

    }).catch(err => {
      this.setState({
        loading: false
      });
      throw new Error(err);
    });
  }

  render() {
    const { errorMsg, loading } = this.state;
    return (
      <div className="login-page" onKeyPress={e => {
        if (e.which === 13 && e.target.type === 'password') {
          this.LoginForm.loginSubmit();
        }
      }}>
        <div className="login-header">
          <div className="logo">
            广告业务后台管理系统
          </div>
        </div>
        <div className="login-content-wrap">
          <div className="login-content">
            <div className="word">广告 <br />让想象发生</div>
            <div className="login-box">
              <div className="title">账号登录</div>
              <LoginForm wrappedComponentRef={inst => { this.LoginForm = inst; }} loginSubmit={this.loginReq} errorMsg={errorMsg} loading={loading}/>
            </div>
          </div>
        </div>
        <footer>
          <span>Copyright ©️ 2018 keruyun Inc. All rights reserved.京ICP备12039470号</span>
        </footer>
      </div>
    )
  }
}

class LoginForm extends React.Component {
  state = {}

  loginSubmit = (e) => {
    e && e.preventDefault();
    const _this = this;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        var formValue = _this.props.form.getFieldsValue();
        _this.props.loginSubmit({
          userName: formValue.username,
          password: formValue.password
        });
      }
    });
  }

  checkUsername = (rule, value, callback) => {
    const reg = /^[a-z0-9]+([._\\-]*[a-z0-9])*@(keruyun.com|shishike.com)$/;
    if (!value) {
      callback('请输入用户名!');
    // } else if (!reg.test(value)) {
    //   callback('请使用客如云邮箱(test@keruyun.com|shishike.com)进行登录');
    } else {
      callback();
    }
  }

  checkPassword = (rule, value, callback) => {
    if (!value) {
      callback('请输入密码!');
    } else {
      callback();
    }
  }

  render() {
    const {
      getFieldDecorator
    } = this.props.form;
    const { errorMsg, loading } = this.props;
    const colorStyle = { color: 'rgba(0,0,0,.25)' };
    const FormItemStyle = {  margin: 0 };
    return (
      <Form className="login-form">
        {errorMsg? (
          <FormItem style={FormItemStyle}>
            {getFieldDecorator('errMessage')(
              <span className='errMessage'>{errorMsg}</span>
            )}
          </FormItem>
        ) : null}
        <FormItem>
          {getFieldDecorator('username', {
            initialValue: '',
            rules: [{validator: this.checkUsername}]
          })(
            <Input prefix={<Icon type="user" style={colorStyle} />} placeholder="用户名"/>
          )}
        </FormItem>
        <FormItem>
          {getFieldDecorator('password', {
            initialValue: '',
            rules: [{validator: this.checkPassword}]
          })(
            <Input prefix={<Icon type="lock" style={colorStyle}  />}type="password" placeholder="密码"/>
          )}
        </FormItem>
        <FormItem>
          <Button loading={loading} type="primary" onClick={this.loginSubmit} className="login-form-button">
            {!loading ? '登录' : '登录中'}
          </Button>
        </FormItem>
      </Form>
    )
  }
}
LoginForm = Form.create({})(LoginForm);
